package com.tic.robot.ui.fragment;


import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.tic.robot.R;
import com.tic.robot.core.BluetooshManager;
import com.tic.robot.entity.BluetoothMsg;
import com.tic.robot.entity.ChatMessage;
import com.tic.robot.ui.adapter.ClientAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

/**
 * Created by Administrator on 2016/9/24.
 */
public class ConnectFragment extends Fragment {

    private ListView mListView;

    private ArrayList<ChatMessage> mList;

    private ClientAdapter mClientAdapter; // ListView适配器

    private BluetoothAdapter mBluetoothAdapter; // Bluetooth适配器

    private BluetoothDevice mBluetoothDevice; // 蓝牙设备

    private ClientThread mClientThread; // 客户端运行线程

    public static ConnectFragment newInstance() {
        return new ConnectFragment();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_connect, container, false);
        initView(root);
        return root;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                // 发送打开蓝牙的意图，系统会弹出一个提示对话框
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, Activity.RESULT_FIRST_USER);

                // 设置蓝牙的可见性，最大值3600秒，默认120秒，0表示永远可见(作为客户端，可见性可以不设置，服务端必须要设置)
                Intent displayIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                displayIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
                startActivity(displayIntent);

                // 直接打开蓝牙
                mBluetoothAdapter.enable();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 扫描
        scanDevice();
    }

    // 扫描设备
    private void scanDevice() {
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        } else {
            mList.clear();
            mClientAdapter.notifyDataSetChanged();

            // 每次扫描前都先判断一下是否存在已经配对过的设备
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    mList.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), true));
                    mClientAdapter.notifyDataSetChanged();
                    mListView.setSelection(mList.size() - 1);
                }
            } else {
                mList.add(new ChatMessage("No devices have been paired", true));
                mClientAdapter.notifyDataSetChanged();
                mListView.setSelection(mList.size() - 1);
            }
            /* 开始搜索 */
            mBluetoothAdapter.startDiscovery();
        }
    }

    private void initView(View view) {

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        view.findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanDevice();
            }
        });

        mList = new ArrayList<ChatMessage>();
        mClientAdapter = new ClientAdapter(getContext(), mList);
        mListView = (ListView) view.findViewById(R.id.list);
        mListView.setFastScrollEnabled(true);
        mListView.setAdapter(mClientAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChatMessage item = mList.get(position);
                String info = item.getMessage();
                String address = info.substring(info.length() - 17);
                BluetoothMsg.BlueToothAddress = address;

                // 停止扫描
                // BluetoothAdapter.startDiscovery()很耗资源，在尝试配对前必须中止它
                mBluetoothAdapter.cancelDiscovery();

                // 通过Mac地址去尝试连接一个设备
                mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(BluetoothMsg.BlueToothAddress);
                mClientThread = new ClientThread();
                mClientThread.start();
                BluetoothMsg.isOpen = true;
            }
        });

        // 注册receiver监听
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mReceiver, filter);

        // 获取已经配对过的蓝牙设备
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                mList.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), true));
                mClientAdapter.notifyDataSetChanged();
                mListView.setSelection(mList.size() - 1);
            }
        } else {
            mList.add(new ChatMessage("没有已经配对过的设备", true));
            mClientAdapter.notifyDataSetChanged();
            mListView.setSelection(mList.size() - 1);
        }

    }

    /**
     * 蓝牙设备扫描过程中(mBluetoothAdapter.startDiscovery())会发出的消息 ACTION_FOUND 扫描到远程设备
     * ACTION_DISCOVERY_FINISHED 扫描结束
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds devices
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                // 通过EXTRA_DEVICE附加域来得到一个BluetoothDevice设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed
                // already
                // 如果这个设备是不曾配对过的，添加到list列表
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mList.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), false));
                    mClientAdapter.notifyDataSetChanged();
                    mListView.setSelection(mList.size() - 1);
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                getActivity().setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0) {
                    mList.add(new ChatMessage("没有发现蓝牙设备", false));
                    mClientAdapter.notifyDataSetChanged();
                    mListView.setSelection(mList.size() - 1);
                }
            }
        }
    };

    // Handler更新UI
    private Handler LinkDetectedHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // Toast.makeText(mContext, (String)msg.obj,
            // Toast.LENGTH_SHORT).show();
            if (msg.what == 1) {
                mList.add(new ChatMessage((String) msg.obj, true));
            } else {
                mList.add(new ChatMessage((String) msg.obj, false));
            }
            mClientAdapter.notifyDataSetChanged();
            mListView.setSelection(mList.size() - 1);

        }

    };


    // 开启客户端连接服务端
    private class ClientThread extends Thread {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mBluetoothDevice != null) {
                try {
                    BluetooshManager.getInstance().setSocket(mBluetoothDevice.createRfcommSocketToServiceRecord(UUID
                            .fromString("00001101-0000-1000-8000-00805F9B34FB")));
                    // 连接
                    Message msg = new Message();
                    msg.obj = "请稍候，正在连接服务器: " + BluetoothMsg.BlueToothAddress;
                    msg.what = 0;
                    LinkDetectedHandler.sendMessage(msg);

                    // 通过socket连接服务器，这是一个阻塞过程，直到连接建立或者连接失效
                    BluetooshManager.getInstance().getSocket().connect();

                    Message msg2 = new Message();
                    msg2.obj = "已经连接上服务端！可以发送信息";
                    msg2.what = 0;
                    LinkDetectedHandler.sendMessage(msg2);

                } catch (IOException e) {
                    Message msg = new Message();
                    msg.obj = "连接服务端异常！断开连接重新试一试。";
                    msg.what = 0;
                    LinkDetectedHandler.sendMessage(msg);
                    BluetooshManager.getInstance().closeSocket();
                }
            }
        }
    }
}
